package com.boruan.shengtangfeng.api.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dao.IConfigDao;
import com.boruan.shengtangfeng.core.dto.ModuleRecordDto;
import com.boruan.shengtangfeng.core.dto.QuestionCommentDto;
import com.boruan.shengtangfeng.core.dto.QuestionCommentPageSearch;
import com.boruan.shengtangfeng.core.dto.QuestionPageSearch;
import com.boruan.shengtangfeng.core.dto.mapper.ModuleRecordDtoMapper;
import com.boruan.shengtangfeng.core.dto.mapper.QuestionCommentDtoMapper;
import com.boruan.shengtangfeng.core.entity.Module;
import com.boruan.shengtangfeng.core.entity.ModuleRecord;
import com.boruan.shengtangfeng.core.entity.PopularWords;
import com.boruan.shengtangfeng.core.entity.Question;
import com.boruan.shengtangfeng.core.entity.QuestionComment;
import com.boruan.shengtangfeng.core.entity.Subject;
import com.boruan.shengtangfeng.core.entity.User;
import com.boruan.shengtangfeng.core.service.IConfigService;
import com.boruan.shengtangfeng.core.service.IModuleRecordService;
import com.boruan.shengtangfeng.core.service.IModuleService;
import com.boruan.shengtangfeng.core.service.IPopularWordsService;
import com.boruan.shengtangfeng.core.service.IQuestionCommentService;
import com.boruan.shengtangfeng.core.service.IQuestionRecordService;
import com.boruan.shengtangfeng.core.service.IQuestionService;
import com.boruan.shengtangfeng.core.service.ISearchWordsService;
import com.boruan.shengtangfeng.core.service.ISubjectService;
import com.boruan.shengtangfeng.core.service.IUserService;
import com.boruan.shengtangfeng.core.utils.CommentUtil;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.StringUtils;
import com.boruan.shengtangfeng.core.vo.ModuleRankVo;
import com.boruan.shengtangfeng.core.vo.PopularWordsVo;
import com.boruan.shengtangfeng.core.vo.QuestionCommentVo;
import com.boruan.shengtangfeng.core.vo.QuestionVo;
import com.boruan.shengtangfeng.core.vo.mapper.PopularWordsMapper;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionCommentVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: lihaicheng
 * @Description: 登录
 * @date:2020年3月10日 上午11:14:10
 */
@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/api/question")
@Api(value = "", tags = { "NO:4 做题相关接口" })
public class QuestionApi {
    @Autowired
    private IModuleService moduleService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuestionCommentService questionCommentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IQuestionRecordService questionRecordService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IModuleRecordService moduleRecordService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IConfigDao configDao;
    @Autowired
    private IPopularWordsService popularWordsService;
    @Autowired
    private ISearchWordsService searchWordsService;
    @Autowired
    private ISubjectService subjectService;


    @GetMapping("/pageQuestion")
    @ApiOperation(value = "NO:4-19 分页查询试题", notes = "")
    public GlobalReponse<PageQuery<Question>> pageQuestion(
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, Question question) {
        PageQuery<Question> pageQuery = new PageQuery<Question>();
        pageQuery.setPageNumber(pageNo);
        questionService.pageQuery(pageQuery, question);
        return GlobalReponse.success(pageQuery);
    }


//
//    @GetMapping("/searchQuestion")
//    @ApiOperation(value = "NO:4-20 查询试题，用于检索等功能", notes = "")
//    public GlobalReponse<PageQuery<Question>> searchQuestion(
//            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, String keyword) {
//        if(StringUtils.isBlank(keyword)) {
//            return GlobalReponse.fail("检索词不能为空");
//        }
//        PageQuery<Question> pageQuery = new PageQuery<Question>();
//        pageQuery.setPageNumber(pageNo);
//        Question search = new Question();
//        search.set("keyword", keyword);
//        questionService.pageQuery(pageQuery, search);
//        List<Question> questions=pageQuery.getList();
//        List<QuestionVo> vos=QuestionVoMapper.MAPPER.toVo(questions);
//        vos.forEach(vo->{
////            搜索命中类型 0题干   1 所有 2 内容
//            if(StringUtils.contains(vo.getTitle(), keyword)) {
//                vo.setHitType(0);
//                vo.setTitle(StringUtils.replaceAll(vo.getTitle(),keyword,"<font color='red'>"+keyword+"</font>"));
//            }
//            if(StringUtils.contains(vo.getContent(), keyword)) {
//                if(vo.getHitType()!=null) {
//                    vo.setHitType(1);
//                }else {
//                    vo.setHitType(2);
//                }
//                vo.setContent(StringUtils.replaceAll(vo.getContent(),keyword,"<font color='red'>"+keyword+"</font>"));
//            }
//        });
//        vos.sort((x, y) -> Double.compare(x.getHitType(), y.getHitType()));
//        pageQuery.setList(vos);
//        return GlobalReponse.success(pageQuery);
//    }
//
//    @PostMapping("/answerQuestion")
//    @ApiOperation(value = "NO:4-21 单道题答题，客观题返回结果，添加参数，答对后移除错题，用于错题本答题 ,data返回是否正确，data1返回做题获得的奖励金额", notes = "")
//    public GlobalReponse<Boolean> answerQuestion(QuestionRecordDto questionRecordDto,HttpServletRequest request) {
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        User user = userService.findById(userSubject.getId());
//        Boolean tips=false;
//        Question question = questionService.findById(questionRecordDto.getQuestionId());
//        QuestionRecord record = QuestionRecordDtoMapper.MAPPER.toEntity(questionRecordDto);
//        record.setUserAnswer(null);
//        record.setScore(null);
//        record.setUserId(userSubject.getId());
//        List<QuestionRecord> old = questionRecordService.template(record);
//        if (old != null && !old.isEmpty()) {
//            record=old.get(0);
//        }
//        BigDecimal reward=null;
//        // 非主观题判断答案
//        if (questionRecordDto.getUserAnswer()!=null&&StringUtils.equalsIgnoreCase(questionRecordDto.getUserAnswer(), question.getAnswer())) {
//            record.setCorrect(true);
//            //答对后移除错题
//            if (questionRecordDto.isRemoveCorrect()) {
//                questionService.removeIncorrect(questionRecordDto.getQuestionId(), userSubject.getId());
//            }
//            //更新用户做题记录
//            if(user.getCorrectNum()==null){
//                user.setCorrectNum(0);
//            }
//            user.setCorrectNum(user.getCorrectNum()+1);
//            user.setAnswerNum(user.getAnswerNum()+1);
//            userService.save(user);
//        } else {
//            if(user.getCorrectNum()==null){
//                user.setCorrectNum(0);
//            }
//            user.setIncorrectNum(user.getCorrectNum()+1);
//            user.setAnswerNum(user.getAnswerNum()+1);
//            userService.save(user);
//            record.setCorrect(false);
//            // 错题记录
//            IncorrectQuestion incorrectQuestion = new IncorrectQuestion();
//            incorrectQuestion.setQuestionId(questionRecordDto.getQuestionId());
//            incorrectQuestion.setUserId(userSubject.getId());
//            incorrectQuestion.setCreateBy(userSubject.getMobile());
//            incorrectQuestion.setAnswer(questionRecordDto.getUserAnswer());
//            incorrectQuestion.setIsDeleted(false);
//            incorrectQuestion.setType(question.getType());
//            incorrectQuestion.setCreateTime(new Date());
//            questionService.saveIncorrect(incorrectQuestion);
//        }
//        record.setUserAnswer(questionRecordDto.getUserAnswer());
//        record.setCreateBy(user.getMobile());
//        record.setCreateTime(new Date());
//        record.setIsDeleted(false);
//        record.setUserId(user.getId());
//        record.setUserName(user.getName());
//        questionRecordService.save(record);
//        return GlobalReponse.success(record.getCorrect()).setData1(reward).setData2(tips);
//    }

    @PostMapping("/favorites/{moduleId}/{questionId}")
    @ApiOperation(value = "NO:4-1 收藏试题", notes = "")
    public GlobalReponse<Boolean> favorites(@PathVariable("moduleId") Long moduleId,@PathVariable("questionId") Long questionId,HttpServletRequest request) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        String token=jwtUtil.getToken(request);
        
        questionService.addFavorites(moduleId,questionId, userSubject.getId());
        return GlobalReponse.success("收藏成功");
    }

    @PostMapping("/removeFavorites/{questionId}")
    @ApiOperation(value = "NO:4-2 取消收藏试题", notes = "")
    public GlobalReponse<Boolean> removeFavorites(@PathVariable("questionId") Long questionId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        questionService.removeFavorites(questionId, userSubject.getId());
        return GlobalReponse.success("取消收藏成功");
    }


//    @GetMapping("/getFavoritesQuestion")
//    @ApiOperation(value = "NO:4-3 获取收藏的试题", notes = "")
//    public GlobalReponse<List<QuestionVo>> getFavoritesQuestion(HttpServletRequest request) {
//        GlobalReponse response=GlobalReponse.success();
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        User user=userService.findById(userSubject.getId());
//        String token=jwtUtil.getToken(request);
//        //默认只有单选题
//        List<Question> questions = questionService.getFavoritesList(userSubject.getId(), QuestionType.DANXUANTI.getValue());
//        List<QuestionVo> vos = QuestionVoMapper.MAPPER.toVo(questions);
//        response.setData(vos);
//        return response;
//    }
    
    @PostMapping("/getQuestionComment")
    @ApiOperation(value = "NO:4-4 获取题目下的评论", notes = "")
    public GlobalReponse<PageQuery<QuestionCommentVo>> getQuestionComment(@RequestBody QuestionCommentPageSearch pageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        QuestionComment comment=new QuestionComment();
        PageQuery<QuestionComment> pageQuery = new PageQuery<QuestionComment>();
        pageQuery.setPageNumber(pageSearch.getPageNo());
        pageQuery.setPageSize(pageSearch.getPageSize());
        QuestionComment search=new QuestionComment();
        search.setQuestionId(pageSearch.getQuestionId());
        search.setStatus(1);
        search.setUserId(userSubject.getId());
        questionCommentService.pageQueryNotMine(pageQuery, search);
        if(pageSearch.getPageNo()==1) {
            //用户自己的评论放上面
            search = new QuestionComment();
            search.setIsDeleted(false);
            search.setQuestionId(pageSearch.getQuestionId());
            search.setStatus(1);
            search.setUserId(userSubject.getId());
            List<QuestionComment> notes = questionCommentService.template(search);
            List<QuestionCommentVo> noteVos = QuestionCommentVoMapper.MAPPER.toVo(notes);
            noteVos.addAll(QuestionCommentVoMapper.MAPPER.toVo(pageQuery.getList()));
            pageQuery.setList(noteVos);
        }else {
            pageQuery.setList(QuestionCommentVoMapper.MAPPER.toVo(pageQuery.getList()));
        }
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/comment")
    @ApiOperation(value = "NO:4-5 评论某个题目", notes = "")
    public GlobalReponse<QuestionCommentVo> comment(@RequestBody QuestionCommentDto dto) {
        GlobalReponse globalReponse = null;
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        QuestionComment comment = QuestionCommentDtoMapper.MAPPER.toEntity(dto);
        comment.setCreateBy(userSubject.getMobile());
        comment.setCreateTime(new Date());
        comment.setIsDeleted(false);

        Integer check= CommentUtil.checkComment(comment.getContent());
        if(check==2) {
            comment.setStatus(1);
            globalReponse=GlobalReponse.success(QuestionCommentVoMapper.MAPPER.toVo(comment)).setMessage("评论成功");
            
        }else if(check==1){
            comment.setStatus(0);
            globalReponse=GlobalReponse.fail("您的评论包含敏感词，需要等待客服审核");
        } else if(check==0){
            return GlobalReponse.fail("您的评论包含敏感词禁止评论");
        }
        comment.setUserId(userSubject.getId());
        comment.setUserName(userSubject.getName());
        comment.setUserIcon(userSubject.getIcon());
        comment.autoSetType();
        questionCommentService.save(comment);
        return globalReponse;
    }
    
    @PostMapping("/deleteComment/{commentId}")
    @ApiOperation(value = "NO:4-6 删除评论", notes = "")
    public GlobalReponse<Boolean> deleteComment(@PathVariable("commentId") Long commentId,HttpServletRequest request) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        String token=jwtUtil.getToken(request);
        
        QuestionComment comment=questionCommentService.findById(commentId);
        if(comment.getUserId().equals(userSubject.getId())) {
            comment.setIsDeleted(true);
            comment.setUpdateTime(new Date());
            comment.setUpdateBy(userSubject.getName());
            questionCommentService.save(comment);
            return GlobalReponse.success("删除评论成功");
        }else {
            return GlobalReponse.fail("删除失败，不能删除其他人的评论");
        }
        
    }

    @PostMapping("/addIncorrectQuestion/{moduleId}/{questionId}")
    @ApiOperation(value = "NO:4-7 添加错题", notes = "")
    public GlobalReponse<Boolean> addIncorrectQuestion(@PathVariable("moduleId") Long moduleId,@PathVariable("questionId") Long questionId,HttpServletRequest request) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        questionService.addIncorrect(moduleId,questionId, userSubject.getId());
        return GlobalReponse.success("添加成功");

    }
    @PostMapping("/delIncorrectQuestion/{questionId}")
    @ApiOperation(value = "NO:4-14 删除错题", notes = "")
    public GlobalReponse<Boolean> delIncorrectQuestion(@PathVariable("questionId") Long questionId,HttpServletRequest request) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        questionService.delIncorrect(questionId, userSubject.getId());
        return GlobalReponse.success("删除成功");
    }
    
//    @GetMapping("/getIncorrectQuestion")
//    @ApiOperation(value = "NO:4-8 获取错误的试题", notes = "")
//    public GlobalReponse<List<QuestionVo>> getIncorrectQuestion(Integer type,HttpServletRequest request) {
//        GlobalReponse response=GlobalReponse.success();
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        User user=userService.findById(userSubject.getId());
//        List<Question> questions = questionService.getIncorrectList(userSubject.getId(), type);
//        List<QuestionVo> vos = QuestionVoMapper.MAPPER.toVo(questions);
//        response.setData(vos);
//        return response;
//    }
//
    @PostMapping("/commitModule")
    @ApiOperation(value = "NO:4-9 提交练习结果,data返回当次练习结果，取moduleId用于查看排行,data1返回下一个模块的ID用于继续练习", notes = "")
    public GlobalReponse<ModuleRecord> commitModule(@RequestBody ModuleRecordDto dto) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        ModuleRecord search=new ModuleRecord();
        search.setUserId(userSubject.getId());
        search.setModuleId(dto.getModuleId());
        search.setIsDeleted(false);
        ModuleRecord moduleRecord= moduleRecordService.templateOne(search);
        if(moduleRecord==null) {
            moduleRecord=ModuleRecordDtoMapper.MAPPER.toEntity(dto);
            moduleRecord.setIsDeleted(false);
            Module module=moduleService.findById(dto.getModuleId());
            moduleRecord.setParentModuleId(module.getParentId());
            moduleRecord.setUserId(userSubject.getId());
            moduleRecord.setUserIcon(userSubject.getIcon());
            moduleRecord.setUserName(userSubject.getName());
            moduleRecord.setCreateTime(new Date());
            moduleRecord.setCreateBy(userSubject.getName());
            moduleRecordService.save(moduleRecord);
            //第一次做完要计算完成数
            module.setCompleteCount((module.getCompleteCount()==null?0:module.getCompleteCount())+1);
            moduleService.save(module);
            
            
            Module searchModule = new Module();
            searchModule.setParentId(module.getParentId());
            List<Module> modules=moduleService.findByCondition(searchModule);
            ModuleRecord moduleRecordSearch=new ModuleRecord();
            moduleRecordSearch.setParentModuleId(module.getParentId());
            moduleRecordSearch.setUserId(userSubject.getId());
            Long count=moduleRecordService.templateCount(moduleRecordSearch);
            //父模块下的模块全部完成了，则父模块已完成+1
            if(modules.size()==count.intValue()) {
                Module parentModule=moduleService.findById(module.getParentId());
                parentModule.setCompleteCount((parentModule.getCompleteCount()==null?0:parentModule.getCompleteCount())+1); 
                moduleService.save(parentModule);
            }
        }else {
            moduleRecord.setIntegral(dto.getIntegral());
            moduleRecord.setScore(dto.getScore());
            moduleRecord.setTime(dto.getTime());
            moduleRecord.setUpdateTime(new Date());
            moduleRecord.setUpdateBy(userSubject.getName());
            moduleRecordService.save(moduleRecord);
        }
        //更新用户积分
        User user=userService.findById(userSubject.getId());
        user.setIntegral(user.getIntegral()+dto.getIntegral());
        userService.save(user);
        //获取下一模块的ID用于继续练习
        Module module =moduleService.findNext(dto.getModuleId());
        return GlobalReponse.success("提交成功",moduleRecord).setData1(module.getId());
    }
    @PostMapping("/getRank/{moduleId}")
    @ApiOperation(value = "NO:4-10 获取本次答题排名", notes = "")
    public GlobalReponse<ModuleRankVo> getRank(@PathVariable("moduleId") Long moduleId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        ModuleRankVo vo=moduleRecordService.getRank(moduleId, userSubject.getId());
        return GlobalReponse.success(vo);
    }
    @PostMapping("/getRankAll")
    @ApiOperation(value = "NO:4-11 获取总答题排名", notes = "")
    public GlobalReponse<ModuleRankVo> getRankAll() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        ModuleRankVo vo=moduleRecordService.getRankAll(userSubject.getId());
        return GlobalReponse.success(vo);
    }
//    @GetMapping("/getQuestionStatictics")
//    @ApiOperation(value = "NO:4-38 获取用户答题统计", notes = "")
//    public GlobalReponse<QuestionStaticticsVo> getQuestionStatictics() {
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        User user = userService.findById(userSubject.getId());
//        QuestionStaticticsVo staticticsVo = new QuestionStaticticsVo();
//        float num=(float)user.getCorrectNum()/user.getAnswerNum();
//
//        staticticsVo.setAccurate((int) (num*100));
//        staticticsVo.setAnswerNum(user.getAnswerNum());
//        staticticsVo.setCorrectNum(user.getCorrectNum());
//        staticticsVo.setIncorrectNum(user.getIncorrectNum());
//        staticticsVo.setQuestionNum(questionService.getQuestionCount());
//        return GlobalReponse.success(staticticsVo);
//    }
    /**
     * @description: 获取试题热门词
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/13 17:10
     */
    @PostMapping("getPopularWords")
    @ApiOperation(value = "NO:4-12 获取试题热门词 ", notes = "")
    public GlobalReponse<List<PopularWordsVo>> getPopularWords() {
//        关键字类型1试题2文3视频
        List<PopularWords> popularWordsList = popularWordsService.getList(1);
        return GlobalReponse.success(PopularWordsMapper.MAPPER.toVo(popularWordsList));
    }
    /**
     * @description: 搜索试题
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/13 17:10
     */
    @PostMapping("search")
    @ApiOperation(value = "NO:4-13 搜索试题 ", notes = "")
    public GlobalReponse<PageQuery<QuestionVo>> search(@RequestBody QuestionPageSearch questionPageSearch) {
        Question search=new Question();
        PageQuery<Question> pageQuery = new PageQuery<Question>();
        List<Question> list= null;
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        search.set("keyword", questionPageSearch.getKeyword());
        if(userSubject!=null&&StringUtils.isNotBlank(questionPageSearch.getKeyword())) {
            searchWordsService.addSearchWord(userSubject.getId(), 1, questionPageSearch.getKeyword());
        }
        pageQuery.setPageNumber(questionPageSearch.getPageNo());
        questionService.pageQuery(pageQuery, search);
        List<QuestionVo> vos=QuestionVoMapper.MAPPER.toVo(pageQuery.getList());
        vos.forEach(vo->{
            Subject subject=subjectService.get(vo.getSubjectId());
            vo.setSubjectName(subject.getName()+"题");
            List<Module> modules=moduleService.findByQuestion(vo.getId());
            if(modules.isEmpty()) {
                //TODO 不知道该 放什么了，放个0防止空指针
                vo.setModuleId(0L);
            }else {
                vo.setModuleId(modules.get(0).getId());
            }
            vo.setCollect(questionService.isFavorites(userSubject.getId(), vo.getId()));
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    
}
